package com.snap.vseries.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RadioGroup;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.snap.vseries.AppConfig;
import com.snap.vseries.Constants;
import com.snap.vseries.R;
import com.snap.vseries.base.BaseFragment;
import com.snap.vseries.bean.ChannelBean;
import com.snap.vseries.bean.ExpInfo;
import com.snap.vseries.bean.LightBean;
import com.snap.vseries.chart.MyMarkerView;
import com.snap.vseries.manager.ConfigManager;
import com.snap.vseries.ui.widget.ChannelLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

@SuppressLint("ValidFragment")
public class ChartAmpOriginFragment extends BaseFragment {

    @BindView(R.id.chart)
    LineChart chart;
    @BindView(R.id.chart_layout)
    ConstraintLayout chartLayout;
    @BindView(R.id.ll)
    ChannelLayout ll;
    @BindView(R.id.debug_rg)
    RadioGroup debugRg;
    @BindView(R.id.empty_layout)
    FrameLayout emptyLayout;
    private ExpInfo experimentInfo;
    private int lastChannelFlag;
    private String[] contents;
    private MyMarkerView markerView;

    //mode 0 展示给用户看的最终的数值
    //mode 1 最原始的荧光数值
    //mode 2 原始数值叠加倍率
    private int mode = 0;

    public ChartAmpOriginFragment(ExpInfo experimentInfo) {
        this.experimentInfo = experimentInfo;
    }

    @Override
    protected int layoutResId() {
        return R.layout.fragment_chart_amp_origin;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        initViews();
        initData(mode);
        debugOrigin();
        if (experimentInfo.getHoleInfo() == null) {
            return;
        }
        contents = new String[]{experimentInfo.getFamName(), experimentInfo.getVicName(), experimentInfo.getRoxName(), experimentInfo.getCy5Name()};
        ll.initView(contents, experimentInfo.getHoleInfo().getChannelJoinFlag());
    }

    private void debugOrigin() {
        if (AppConfig.Dynamic.exp_running_debug_origin_light) {
            debugRg.setVisibility(View.VISIBLE);
            debugRg.check(R.id.debug1_rb);
            debugRg.setOnCheckedChangeListener((group, checkedId) -> {
                switch (checkedId) {
                    case R.id.debug2_rb://原始
                        mode = 1;
                        break;
                    case R.id.debug3_rb://计算倍率
                        mode = 2;
                        break;
                    default:
                        mode = 0;
                }
                initData(mode);
            });
        } else {
            debugRg.setVisibility(View.GONE);
        }
    }

    private void initViews() {
        //图表整体的一些设置
        chart.setDrawGridBackground(false);
        chart.getDescription().setEnabled(false);
        chart.getLegend().setEnabled(false);
        chart.setDrawBorders(false);
        chart.setMaxVisibleValueCount(0);

        //左右的两根Y轴配置
        chart.getAxisRight().setEnabled(false);
        YAxis yAxis = chart.getAxisLeft();
        yAxis.setEnabled(true);
        yAxis.setDrawAxisLine(true);
        yAxis.setDrawGridLines(true);
        yAxis.setGridColor(0xB3EBECF0);
        yAxis.setTextColor(0xFF999999);
        yAxis.setTextSize(11f);
        yAxis.setGranularity(100f);
        yAxis.setLabelCount(10);

        //X轴配置
        XAxis xAxis = chart.getXAxis();
        xAxis.setEnabled(true);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
//        xAxis.setDrawAxisLine(true);
        xAxis.setDrawGridLines(true);
        xAxis.setGridColor(0xB3EBECF0);
        xAxis.setTextColor(0xFF999999);
        xAxis.setTextSize(11f);
        xAxis.setLabelCount(8);
        xAxis.setGranularity(1f);

        //操作相关
        chart.getViewPortHandler().setMinMaxScaleX(1f, 5f);
        chart.getViewPortHandler().setMinMaxScaleY(1f, 5f);
        chart.setTouchEnabled(true);
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setPinchZoom(true);
        // 设置默认右下角的描述
//        Description description=new Description();
//        description.setText("这是一个表格");
//        description.setPosition(0,0);
//        chart.setDescription(description);
        // 设置Legend
        markerView = new MyMarkerView(getContext(), R.layout.custom_marker_view, 0);
        chart.setMarker(markerView);
        chart.setDrawMarkers(true);
        chart.invalidate();
    }

    private void initData(int mode) {
        if (mode == 0 && (experimentInfo.getHoleInfo() == null || experimentInfo.getHoleInfo().getChannelData() == null)) {
            hasData(false);
            return;
        }
        if (mode != 0 && experimentInfo.getLightData() == null) return;
        List<ILineDataSet> dataSets = new ArrayList<>();
        for (int i = 0; i < AppConfig.TOTAL_CHANNEL_COUNT; i++) {
            //不论有没有参与实验 先添加 方便对应上关系
            LineDataSet dataSet = new LineDataSet(new ArrayList<>(), (i + 1) + "");
            dataSets.add(dataSet);
            int whichChannel = i;
            boolean enable = (experimentInfo.getHoleInfo().getChannelJoinFlag() >> whichChannel & 0x01) == 0x01;
            if (enable) {
                dataSet.setMode(LineDataSet.Mode.LINEAR);//线的样式
                dataSet.setLineWidth(2f);//线宽
                dataSet.setColor(Constants.CHANNEL_DEFAULT_COLORS[i / AppConfig.TOTAL_HOLE_COUNT % AppConfig.TOTAL_CHANNEL_COUNT]);
                dataSet.setDrawValues(false);
                Bundle b = new Bundle();
                b.putInt("channelIndex", whichChannel + 1);
                b.putInt("holeIndex", i % AppConfig.TOTAL_HOLE_COUNT + 1);
                if (mode == 0) {
                    //有数据 并且 该通道该孔参与实验'
                    ChannelBean bean = experimentInfo.getHoleInfo().getChannelData().get(i);
                    if (bean != null && bean.getOrigin() != null) {
                        for (int j = 0; j < bean.getOrigin().length; j++) {
                            dataSet.addEntry(new Entry(j + 1, bean.getOrigin()[j], b));
                        }
                    }
                } else {
                    List<LightBean> list = experimentInfo.getLightData().get(i + mode * 1000);
                    if (list == null) continue;
                    for (int j = 0; j < list.size(); j++) {
                        dataSet.addEntry(new Entry(j + 1, list.get(j).getIntensity()));
                    }
                }
                dataSet.setDrawCircles(false);//是否画点
                dataSet.setDrawCircleHole(false);
                dataSet.setCircleRadius(2.5f);
                dataSet.setCircleColor(Constants.CHANNEL_DEFAULT_COLORS[i / AppConfig.TOTAL_HOLE_COUNT % AppConfig.TOTAL_CHANNEL_COUNT]);
                //如果只有一条数据，就绘制一个圆点
                if (dataSet.getEntryCount() == 1) {
                    dataSet.setDrawCircles(true);
                } else {
                    dataSet.setDrawCircles(false);
                }
            }
        }

        LineData lineData = new LineData(dataSets);
        chart.setData(lineData);

        resetAxis(lineData.getYMax());

        chart.invalidate();
        hasData(lineData.getEntryCount() > 0);

    }

    private void resetAxis(float yMax) {
        LineData lineData = chart.getLineData();
        XAxis xAxis = chart.getXAxis();
        YAxis yAxis = chart.getAxisLeft();

        //y:0 - setting.lightBase*2.5
        //然后动态调整 x:10的倍数
        //          y:超过base*2.5   maxValue*1.1
        int xMax = lineData.getMaxEntryCountSet().getEntryCount();
        int xRound = (xMax + 9) / 10 * 10;
        xMax = xRound - xMax > 1 ? xRound : xRound + 2;
        xAxis.setAxisMaximum(xMax);
        xAxis.setAxisMinimum(0);

        float yInit = ConfigManager.getInstance().getSettingInfo().getLightBase() * 1.3f;
        if (yMax <= yInit) {
            yMax = yInit;
        } else {
            yMax *= 1.1f;
        }
        yAxis.setAxisMaximum(yMax);
        yAxis.setAxisMinimum(0);
    }

    public void setShowLines(boolean[] bs, int channelFlag) {
        if (chart == null || chart.getData() == null || experimentInfo == null) {
            return;
        }
        chart.post(() -> {
            LineData data = chart.getLineData();
            for (int i = 0; i < bs.length; i++) {
                ILineDataSet lineDataSet = data.getDataSetByIndex(i);
                if (lineDataSet != null) {
                    lineDataSet.setVisible(bs[i]);
                    lineDataSet.setHighlightEnabled(bs[i]);
                }
            }
            int checkOnlyIndex = checkOnly(bs);
            if (checkOnlyIndex >= 0) {
                ILineDataSet lineDataSet = data.getDataSetByIndex(checkOnlyIndex);
                resetAxis(lineDataSet.getYMax());
                lastChannelFlag = -1;
            } else if (channelFlag != 0 && channelFlag != lastChannelFlag) {
                float[] maxArray = new float[AppConfig.TOTAL_CHANNEL_COUNT];
                for (int i = 0; i < bs.length; i++) {
                    int whichChannel = i / AppConfig.TOTAL_HOLE_COUNT;
                    if ((channelFlag >> whichChannel & 0x01) != 0x01) {
                        continue;
                    }
                    ILineDataSet lineDataSet = data.getDataSetByIndex(i);
                    if (lineDataSet != null && lineDataSet.getYMax() > maxArray[whichChannel]) {
                        maxArray[whichChannel] = lineDataSet.getYMax();
                    }
                }
                float maxY = 0f;
                for (int i = 0; i < maxArray.length; i++) {
                    if (maxArray[i] > maxY) {
                        maxY = maxArray[i];
                    }
                }
                resetAxis(maxY);
                lastChannelFlag = channelFlag;
            }
            markerView.update(data);
            data.notifyDataChanged();
            chart.notifyDataSetChanged();
            chart.invalidate();
        });
    }

    /**
     * 是否仅选中单个孔
     * return -2  选中大于1个
     * return -1  无选中
     * return 0~n 选中的序号
     */
    private int checkOnly(boolean[] bs) {
        int counter = 0;
        int lastCheckIndex = -1;
        for (int i = 0; i < bs.length; i++) {
            if (bs[i]) {
                counter++;
                lastCheckIndex = i;
                if (counter > 1) {
                    return -2;
                }
            }
        }
        return lastCheckIndex;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            if (experimentInfo.getHoleInfo().getChannelData() == null) {
                hasData(false);
            } else {
                hasData(chart.getData().getEntryCount() > 0);
            }
        }
    }

    private void hasData(boolean b) {
        emptyLayout.setVisibility(b ? View.GONE : View.VISIBLE);
        ((DetailAnalyzeFragment) getParentFragment()).setGroupLlVisibility(b ? View.VISIBLE : View.GONE);
    }

    public View getAmpOriginView() {
        return chartLayout;
    }
}
